const connect = require('connect')
const serverStaticMiddleware = require('./middlewares/static')
const { createOptimizeDepsRun } = require('../optimizer')
const resolveConfig = require('../config')

async function createServer() {
  const config = await resolveConfig()
  const app = connect()
  console.log(config)
  app.use(serverStaticMiddleware(config))
  const server = {
    async listen(prot, cb) {
      // 在项目启动前进行依赖的预构建
      // 1. 找到本项目依赖的第三方模块
      await runOptimizer(config, server)
      require('http').createServer(app).listen(prot, cb)
    },
  }
  return server
}

async function runOptimizer(config, server) {
  const optimizeDeps = await createOptimizeDepsRun(config)
  server._optimizeDepsMetadata = optimizeDeps.metadata
}

exports.createServer = createServer
